package blue.qingyu.whimurmur.lookBack;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import blue.qingyu.whimurmur.lookBack.model.LookBack;
import blue.qingyu.whimurmur.lookBack.model.LookBackLine;
import blue.qingyu.whimurmur.lookBack.service.LookBackLineServiceProvider;
import blue.qingyu.whimurmur.lookBack.service.LookBackServiceProvider;
import io.jboot.db.model.Columns;
import io.jboot.web.controller.JbootControllerContext;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jpress.JPressConsts;
import io.jpress.core.menu.annotation.AdminMenu;
import io.jpress.core.template.Template;
import io.jpress.core.template.TemplateManager;
import io.jpress.web.base.AdminControllerBase;


@RequestMapping(value = "/admin/addon/trace" ,viewPath = "/")
public class LookBackController extends AdminControllerBase {

	@Inject
	private LookBackServiceProvider traceService;
	
	@Inject
	private LookBackLineServiceProvider traceLineService;

	@ActionKey("/admin/addon/trace/index")
    @AdminMenu(groupId = JPressConsts.SYSTEM_MENU_ADDON, text = "追忆插件")
    public void index() {
    	render("setting/list.html");
    }
	
	public void setting() {
		render("setting/setting.html");
	}

	@Before(Tx.class)
	public void addEditSave() {
		LookBack trace = getModel(LookBack.class);
		Integer id = trace.getId();
		if(id == null) {
			trace.setCreated(new Date());
			trace.setCreatedBy(getLoginedUser().getId().toString());
		}
		traceService.saveOrUpdate(trace);
		
		if(id != null) {
			Db.update("delete from ex_trace_line where trace_header_id = ?", id);
		}
		HttpServletRequest request = JbootControllerContext.get().getRequest();
		String[] images = request.getParameterValues("lookBackLine.image");
		String[] contents = request.getParameterValues("lookBackLine.content");
		List<String> imageList = new ArrayList<String>(Arrays.asList(images));
		List<String> contentList = new ArrayList<String>(Arrays.asList(contents));
		
		for (int i = contentList.size()-1; i >= 0; i--) {
			if(StringUtils.isEmpty(contentList.get(i))) {
				contentList.remove(i);
				imageList.remove(i);
			}
		}
		for(int i = 0; i < contentList.size(); i++) {
			LookBackLine line = new LookBackLine();
			line.setImage(imageList.get(i));
			line.setTraceHeaderId(trace.getId());
			line.setContent(contentList.get(i));
			traceLineService.save(line);
		}
		
		renderOkJson();
	}

	public void addEdit(){
		int id = getParaToInt(0, 0);
		// id为0时新增，大于0时修改
		if(id > 0) {
			LookBack trace = traceService.findById(id);
			setAttr("trace", trace);
		}
		render("setting/addEdit.html");

	}

	@Before(Tx.class)
	public void del(){
		Integer id = getParaToInt(0);
		traceService.deleteById(id);
		Db.update("delete from ex_trace_line where trace_header_id = ?", id);
		renderOkJson();
	}
	
	@Before(Tx.class)
	public void delByIds() {
		Set<String> idsSet = getParaSet("ids");
        for(String idStr: idsSet) {
        	Integer id = Integer.parseInt(idStr);
        	traceService.deleteById(id);
    		Db.update("delete from ex_trace_line where trace_header_id = ?", id);
        }
        renderOkJson();
	}

    /* ----------------------------------------------插件前台文件安装卸载------------------------------------------------ */
	/**
	 * 检查是否安装了插件的前台文件：这个暂时用不到，每次安装时重新安装文件，卸载时删除文件
	 */
	public void checkPlugin() {
    	Template curTemplate = TemplateManager.me().getCurrentTemplate();
    	File templateDir = curTemplate.getAbsolutePathFile();

    	File[] htmls = templateDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".html"));
    	boolean applied = false;
    	for(File html: htmls) {
    		if(html.getName().equals("page_trace.html")) {
    			applied = true;
    			break;
    		}
    	}
    	
		renderJson(Ret.ok().set("code", applied ? 1 : 0));
    }

	/**
	 * 安装插件
	 */
	public void applyPlugin() {
    	Template curTemplate = TemplateManager.me().getCurrentTemplate();
    	File templateDir = curTemplate.getAbsolutePathFile();
		String jpressPath = templateDir.getParentFile().getParent();

    	File pluginResource = new File(jpressPath
    			+ File.separator + "addons" + File.separator + "blue.qingyu.whimurmur.lookback", "install");
    	
    	try
		{
    		for(File resource: pluginResource.listFiles()) {
    			applyPlugin(templateDir, resource);
    		}
    		curTemplate.refresh();
		}
		catch(IOException e)
		{
			e.printStackTrace();
			renderJson(Ret.ok().set("code", 0));
			return;
		}
		
    	renderJson(Ret.ok().set("code", 1));
    }
	
	private void applyPlugin(File to, File from) throws IOException {
		File newFile = new File(to.getAbsolutePath(), from.getName());
		
		if(from.isDirectory()) {
			newFile.mkdir();
			for(File resource: from.listFiles()) {
				applyPlugin(newFile, resource);
			}
		}else {
			Files.copy(from.toPath(), newFile.toPath(), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
		}
	}
    
    public void removePlugin() {
		Template curTemplate = TemplateManager.me().getCurrentTemplate();
		File templateDir = curTemplate.getAbsolutePathFile();
    	String jpressPath = templateDir.getParentFile().getParent();

		// 网站根目录
		File pluginResource = new File(jpressPath
				+ File.separator + "addons" + File.separator + "blue.qingyu.whimurmur.lookback", "install");
		String[] deletes = pluginResource.list();

		deleteFiles(templateDir, deletes);
    	curTemplate.refresh();
    	
    	renderJson(Ret.ok().set("code", 1));
    }
    
    // 从模板中找插件文件（夹）并删除
    private void deleteFiles(File dir, String[] deletes) {
    	for(File f: dir.listFiles()){
    		for(String del: deletes) {
        		if(f.getName().equals(del)) {
        			deletePlugin(f);
        		}
        	}
    	}
    }
    
    // 删除插件文件（夹）
    private void deletePlugin(File dir) {
    	if(dir.isDirectory()) {
    		for(File f: dir.listFiles()) {
    			if(f.isFile()) {
    				f.delete();
    			}else {
    				deletePlugin(f);
    			}
    		}
    	}
    	
    	dir.delete();
    }
}
